package com.cyys.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyys.entity.*;
import com.cyys.response.Result;
import com.cyys.service.CategoryGoodsService;
import com.cyys.service.OrdersService;
import com.cyys.service.ShoppingCartService;
import com.cyys.service.SitesService;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.github.classgraph.json.JSONUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Long
 * @since 2022-06-17
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private CategoryGoodsService categoryGoodsService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private SitesService sitesService;

    /**
     * 查询全部
     * @return
     */
    @GetMapping("/list")
    public Result list(Integer id) {
        List<Orders> list = ordersService.getOrdersList(id);
        if (list.size()==0) {
            return Result.error().message("没有待支付状态的订单");
        }
        return Result.ok().data("list", list);
    }

    @ApiOperation(value = "添加订单")
    @PostMapping ("/add/{sid}")
    public Result add(@PathVariable Integer sid, @RequestBody List<ShoppingCart> shoppingCartList ){


        Sites byId1 = sitesService.getById(sid);

        shoppingCartList.forEach(System.out::println);
        Orders orders =new Orders();
        List<Integer> ids=new ArrayList<>();
        orders.setMini_id(shoppingCartList.get(0).getUser_id()+"");
        double sum=0;
        int num=0;

        Integer ids2 = 0;
        for (ShoppingCart cart:shoppingCartList){
            ids.add(cart.getId());
            sum+=cart.getNumber()*cart.getAmount();
            num+=cart.getNumber();
            CategoryGoods byId = categoryGoodsService.getById(cart.getDish_id());
            ids2=byId.getStoreId();
        }
        orders.setTime(Date.from( LocalDateTime.now().atZone( ZoneId.systemDefault()).toInstant()));
        orders.setPrice(sum);
        orders.setSum(num+"");
        orders.setStatus(0+"");
        orders.setStates_id(1);
        System.out.println(aa(ids));
        orders.setStoreid(ids2);
        orders.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
        orders.setShopping_cart_id(aa(ids));

        orders.setSex(byId1.getSex());
        orders.setIphone(byId1.getIphone());
        orders.setName(byId1.getName());
        orders.setProfile(byId1.getProfile());
        orders.setSite(byId1.getSite());
        ordersService.save(orders);

        return Result.ok().message("ok");
    }

    /**
     * 查询当前用户全部订单
     * @return
     */
    @GetMapping("/listMini")
    public Result listMini(Integer mini_id) {
        List<Orders> list = ordersService.getOrdersListMini(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }

    /**
     * 查询当前id订单详情
     * @return
     */
    @GetMapping("/listId")
    public Result listId(Integer id) {
        List<Orders> list = ordersService.listId(id);
        Date date = new Date();
        System.out.println(date);
        //取消的时间
        Long time= Long.valueOf( 60 * 1000);

        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();
            Date orderTime = a1.getTime();
            System.out.println(orderTime.getTime());
            a1.setTime_ms(time-(date.getTime()-orderTime.getTime()));
            System.out.println(a1);
            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        System.out.println(time);

        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }



    public List<Integer> aaa(String value){
        List<Integer> list=new ArrayList<>();
        String value1=value.substring(1,value.length()-1);
        String[] values=value1.split(",");
        for (String ss:values){
            list.add(Integer.parseInt(ss.substring(1,ss.length()-1)));
        }
        return list;
    }



    public String aa(List<Integer> ids){
        String b="";
        for (int a=0;a<ids.size();a++){
            if (a==0){
                if (ids.size()==1){
                    b+="[\""+ids.get(a)+"\"]";
                }else {
                    b+="[\""+ids.get(a)+"\",";
                }
            }else if (a==ids.size()-1){
                b+="\""+ids.get(a)+"\"]";
            }else {
                b+="\""+ids.get(a)+"\",";
            }
        }
        return b;
    }


    /**
     * 待付款订单
     * @return
     */
    @GetMapping("/listStatesId1")
    @ApiOperation(value = "待付款订单")
    public Result listStatesId1(Integer mini_id) {
        List<Orders> list = ordersService.listStatesId1(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }
    /**
     * 待发货订单
     * @return
     */
    @GetMapping("/listStatesId2")
    @ApiOperation(value = "待发货订单")
    public Result listStatesId2(Integer mini_id) {
        List<Orders> list = ordersService.listStatesId2(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }

    /**
     * 已发货订单
     * @return
     */
    @GetMapping("/listStatesId3")
    @ApiOperation(value = "已发货订单")
    public Result listStatesId3(Integer mini_id) {
        List<Orders> list = ordersService.listStatesId3(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }

    /**
     * 已完成订单
     * @return
     */
    @GetMapping("/listStatesId4")
    @ApiOperation(value = "已完成订单")
    public Result listStatesId4(Integer mini_id) {
        List<Orders> list = ordersService.listStatesId4(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }

    /**
     * 已取消订单
     * @return
     */
    @GetMapping("/listStatesId5")
    @ApiOperation(value = "已取消订单")
    public Result listStatesId5(Integer mini_id) {
        List<Orders> list = ordersService.listStatesId5(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }

    /**
     * 退款订单
     * @return
     */
    @ApiOperation(value = "退款订单")
    @GetMapping("/listStatesId6")
    public Result listStatesId6(Integer mini_id) {
        List<Orders> list = ordersService.listStatesId6(mini_id);
        list.forEach(a1->{
            List<Integer> aaa = aaa(a1.getShopping_cart_id());
            List<ShoppingCart> shoppingCartList=new ArrayList<>();

            aaa.forEach(a2->{
                ShoppingCart byId = shoppingCartService.findList(a2);
                shoppingCartList.add(byId);
            });
            a1.setShoppingCarts(shoppingCartList);
        });
        if (list.size()==0) {
            return Result.error().message("没有当前用户全部订单");
        }
        return Result.ok().data("list", list);
    }

    /**
     * 根据订单id修改订单状态
     * @param did
     * @param states_id
     * @return
     */
    @PutMapping("/updateStates/{did}/{states_id}")
    public Result updateStates(
            @PathVariable Integer did,
            @PathVariable Integer states_id
    )
    {
        System.out.println(did);
        System.out.println(states_id);
        UpdateWrapper<Orders> uw= new UpdateWrapper<>();
        uw.eq("id",did);
        uw.set("states_id",states_id);

        ordersService.update(uw);
        return Result.ok();
    }


}

